//
//  VisitorViewController.m
//  AlinkDemo
//
//  Created by Vincent on 2017/10/29.
//  Copyright © 2017年 aliyun. All rights reserved.
//

#import "VisitorEditViewController.h"
#import <FSCalendar.h>
#import "PopCalendarViewController.h"
#import "VisitorTableViewCell.h"
#import <MWPhotoBrowser.h>
#import <ZipArchive.h>
#import <AFNetworking.h>
#import "DeleteViewController.h"

@interface VisitorEditViewController ()<UITableViewDelegate,UITableViewDataSource,MWPhotoBrowserDelegate>

@property (weak, nonatomic) IBOutlet UIButton *typeButton;
@property (weak, nonatomic) IBOutlet UIButton *dateButton;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property(nonatomic,retain)NSMutableArray *selectDatas;//接收数据源结果
@property (nonatomic,strong) NSMutableArray *logs;
@property (nonatomic,strong) NSMutableArray *photos;
@property (nonatomic,strong) NSDateFormatter *dateFormatter;


@property (nonatomic,copy) NSString *name;
- (IBAction)buttonClick:(id)sender;
@end

@implementation VisitorEditViewController
static NSString *const cellId = @"logCell";

- (NSMutableArray *)logs{
    
    if (!_logs) {
        _logs = [[NSMutableArray alloc] init];
    }
    
    return _logs;
}

- (NSMutableArray *)selectDatas{
    
    if (!_selectDatas) {
        _selectDatas = [[NSMutableArray alloc] init];
    }
    
    return _selectDatas;
}


- (NSMutableArray *)photos{
    
    if (!_photos) {
        _photos = [[NSMutableArray alloc] init];
    }
    
    return _photos;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    //    self.tabBarController.navigationItem.rightBarButtonItem = [[UIBarButtonItem  alloc] initWithTitle:@"删除" style:UIBarButtonItemStyleDone target:self action:@selector(deleteAction)];
    NSArray *deviceList = [[NSUserDefaults standardUserDefaults] objectForKey:@"DeviceList"];
    if (deviceList) {
        
        for (NSDictionary *device in deviceList) {
            NSString *bid = self.deviceDict[@"bid"];
            NSString *dBid = device[@"bid"];
            if ([bid isEqualToString:dBid]) {
                NSString *nick = device[@"nick"];
                self.name =nick?nick:device[@"name"];
                break;
            }
        }
    }
    
    self.dateFormatter = [[NSDateFormatter alloc] init];
    if (self.isAlarm) {
        [self.typeButton setTitle:@"人体侦测报警" forState:UIControlStateNormal];
    }else{
        [self.typeButton setTitle:@"访客记录" forState:UIControlStateNormal];
        
    }
    
    [self.tableView registerNib:[UINib nibWithNibName:@"VisitorTableViewCell" bundle:nil] forCellReuseIdentifier:cellId];
    
    self.tableView.tableFooterView = [UIView new];
    
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    [self setEditing:YES animated:YES];

}

- (void)closeAction{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)selectAllAction{
    
    if (self.logs.count==0) {
        
        return;
    }
    for (int i = 0; i < self.logs.count; i++) {
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];

        [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionTop];
    }
    [self.selectDatas removeAllObjects];
  
    [self.selectDatas addObjectsFromArray:self.logs];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消全选" style:UIBarButtonItemStyleDone target:self action:@selector(unselectAllAction)];

}

-(void)unselectAllAction{
    if (self.logs.count==0) {
        
        return;
    }
    for (int i = 0; i < self.logs.count; i++) {
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
     
            
        [_tableView deselectRowAtIndexPath:indexPath animated:NO];
    }
    [self.selectDatas removeAllObjects];

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"全选" style:UIBarButtonItemStyleDone target:self action:@selector(selectAllAction)];

}

- (void)deleteAlert{
    
    DeleteViewController *vc= [[DeleteViewController alloc] initWithNibName:@"DeleteViewController" bundle:nil];
    
    __weak typeof(self) weakSelf = self;
    
    vc.conformBlock = ^(BOOL isDelete) {
        
        
        if (weakSelf.isAlarm) {
            
            if (weakSelf.selectDatas.count>0) {
                
                NSString *bid ;
                NSMutableArray *aids = [[NSMutableArray array] init];
                NSString *upzipPath=[ NSSearchPathForDirectoriesInDomains( NSDocumentDirectory , NSUserDomainMask , YES ) objectAtIndex : 0 ];
                NSFileManager *fm = [NSFileManager defaultManager];
                
                for (NSDictionary *dic in weakSelf.selectDatas) {
                    NSLog(@"%@",dic);
                    bid = dic[@"bid"];
                    NSString *fid = dic[@"fid"][0];
                    [aids addObject:dic[@"aid"]];
                    if (isDelete) {
                        upzipPath = [[[upzipPath stringByAppendingPathComponent:weakSelf.isAlarm?@"alarms":@"visitor"] stringByAppendingPathComponent:fid] stringByDeletingPathExtension];
                        [fm removeItemAtPath:upzipPath error:nil];
                    }
                    
                }
                
                [YKBusinessFramework equesDelAlarmMessageWithBid:bid aid:aids delAll:deleteSome];
                
            }
            
        }else{
            if (weakSelf.selectDatas.count>0) {
                
                NSString *bid ;
                NSMutableArray *fids = [[NSMutableArray array] init];
                
                for (NSDictionary *dic in weakSelf.selectDatas) {
                    bid = dic[@"bid"];
                    [fids addObject:dic[@"fid"]];
                    if (isDelete) {
                        NSURL *url = [YKBusinessFramework equesGetRingPictureUrl:dic[@"bid"] fid:dic[@"fid"]];
                        [[SDWebImageManager sharedManager].imageCache removeImageForKey:url.absoluteString fromDisk:YES];
                    }
                }
                
                [YKBusinessFramework equesDelRingRecordWithBid:bid fid:fids delAll:deleteSome];
            }
        }
    };
    
    vc.cancelBlock = ^{
        [weakSelf.selectDatas removeAllObjects];
    };
    
    MZFormSheetPresentationViewController *sheet = [[MZFormSheetPresentationViewController alloc] initWithContentViewController:vc];
    sheet.presentationController.contentViewSize = CGSizeMake(280, 200);
    sheet.presentationController.shouldDismissOnBackgroundViewTap = NO;
    sheet.contentViewCornerRadius=5.f;
    sheet.presentationController.movementActionWhenKeyboardAppears = MZFormSheetActionWhenKeyboardAppearsCenterVertically;
    
    sheet.contentViewControllerTransitionStyle=MZFormSheetPresentationTransitionStyleDropDown;
    sheet.presentationController.shouldCenterVertically= YES;
    sheet.presentationController.shouldCenterHorizontally= YES;
    sheet.willDismissContentViewControllerHandler=^(UIViewController *v){
        
    };
    
    [self presentViewController:sheet animated:YES completion:nil];
    
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated{
    
    [super setEditing:editing animated:animated];
    
    if (!editing) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStyleDone target:self action:@selector(closeAction)];
        
    }else{
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"全选" style:UIBarButtonItemStyleDone target:self action:@selector(selectAllAction)];

    }
    [self.tableView setEditing:!self.tableView.editing animated:YES];
    
    if (!self.tableView.isEditing) {
        if (self.selectDatas.count>0) {
            [self deleteAlert];
        }
    }
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMessageResult:) name:equesOnMessageResultNotification object:nil];
    
    if (self.currentDate) {
        
        [self refresh:self.currentDate];
        
    }else{
        [self.dateFormatter setDateFormat:@"yy-MM-dd 00:00:00"];
        NSString *dateString = [self.dateFormatter stringFromDate:[NSDate date]];
        [self refresh:[self.dateFormatter dateFromString:dateString]];
    }
   
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

-(void)setTableFooterView{
    
    
    if (self.logs.count>0) {
        [self.tableView setTableFooterView:[UIView new]];
        
    }else{
        UIImageView *footerView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH)];
        footerView.contentMode = UIViewContentModeScaleAspectFit;
        if (self.isAlarm) {
            footerView.image = [UIImage imageNamed:@"alarm_no_msg"];
            
        }else{
            footerView.image = [UIImage imageNamed:@"visitor_no_msg"];
            
        }
        [self.tableView setTableFooterView:footerView];
        
    }
    
}

#pragma mark 收到的消息
- (void)onMessageResult:(NSNotification *)notification{
    
    [SVProgressHUD dismiss];
    
    NSDictionary *messageResult = [notification object];
    
    NSString *method = messageResult[@"method"];
    
    if (self.isAlarm) {
        if ([method isEqualToString:@"almlist"]){
            NSInteger code = [messageResult[@"code"] integerValue];
            if (code==4000) {
                
                [self.logs removeAllObjects];
                NSArray *alarms = [messageResult objectForKey:@"alarms"];
                if (alarms.count>0) {
                    [self.logs addObjectsFromArray:alarms];
                }
                
                [self setTableFooterView];
                [self.tableView reloadData];
                
            }else{
                
            }
        }else if ([method isEqualToString:@"delalm"]){
            
            NSInteger code = [messageResult[@"code"] integerValue];
            if (code==4000) {
                [self refresh:self.currentDate];
            }
            
        }
    }else{
        if ([method isEqualToString:@"ringlist"]){
            
            [self.logs removeAllObjects];
            NSArray *alarms = [messageResult objectForKey:@"rings"];
            if (alarms.count>0) {
                [self.logs addObjectsFromArray:alarms];
                
            }
            [self setTableFooterView];
            
            [self.tableView reloadData];
            
        }else if ([method isEqualToString:@"delring"]){
            
            NSInteger code = [messageResult[@"code"] integerValue];
            if (code==4000) {
                [self refresh:self.currentDate];
            }
            
            
        }
        
    }
    
    
}


- (void)refresh:(NSDate *)date{
    [self.dateFormatter setDateFormat:@"MM-dd"];
    NSString *dateString = [self.dateFormatter stringFromDate:date];
    [self.dateButton setTitle:dateString forState:UIControlStateNormal];
    self.currentDate = date;
    
    NSDate *nextDay = [NSDate dateWithTimeInterval:24*60*60 sinceDate:date];//后一天
    long long startTime = ((long long)[date timeIntervalSince1970])*1000;
    long long endTime = ((long long)[nextDay timeIntervalSince1970])*1000;
    
    
    if (self.isAlarm) {
        [YKBusinessFramework equesGetAlarmMessageList:self.deviceDict[@"bid"] startTime:startTime endTime:endTime limitCount:1000];
        
    }else{
        [YKBusinessFramework equesGetRingRecordList:self.deviceDict[@"bid"] startTime:startTime endTime:endTime limitCount:1000];
        
    }
    
}

- (void)downloadImages:(NSDictionary *)logs{
    NSString *bid = logs[@"bid"];
    //    NSString *aid = logs[@"aid"];
    NSString *fid = logs[@"fid"][0];
    
    NSURL *url = [YKBusinessFramework equesGetAlarmfileUrl:bid fid:fid];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *path = [paths[0] stringByAppendingPathComponent:fid];
    
    NSFileManager *fm = [NSFileManager defaultManager];
    if ([fm fileExistsAtPath:path]) {
        
        [self upzip:path fid:fid];
        
    }else{
        
        [SVProgressHUD show];
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
        //allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO//如果是需要验证自建证书，需要设置为YES
        securityPolicy.allowInvalidCertificates = YES;
        //validatesDomainName 是否需要验证域名，默认为YES；
        securityPolicy.validatesDomainName = NO;
        manager.securityPolicy  = securityPolicy;
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        [manager GET:url.absoluteString parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            if (responseObject) {
                
                NSData *data = responseObject;
                [data writeToFile:path atomically:YES];
                
                
                [self upzip:path fid:fid];
                
            }
            [SVProgressHUD dismiss];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@",error);
            [SVProgressHUD dismiss];
        }];
    }
    
    
}

- (void)upzip:(NSString *)path fid:(NSString *)fid {
    
    
    ZipArchive *za = [[ZipArchive alloc] init];
    NSString *upzipPath=[ NSSearchPathForDirectoriesInDomains( NSDocumentDirectory , NSUserDomainMask , YES ) objectAtIndex : 0 ];
    
    upzipPath = [[[upzipPath stringByAppendingPathComponent:self.isAlarm?@"alarms":@"visitor"] stringByAppendingPathComponent:fid] stringByDeletingPathExtension];
    
    if ([za UnzipOpenFile:path])
    {
        BOOL ret = [za UnzipFileTo: upzipPath overWrite: YES];
        NSLog(@"%@",upzipPath);
        if (NO == ret)
        {
            NSLog(@"pir解压失败");
        }
        [za UnzipCloseFile];
        
        NSFileManager *fm = [NSFileManager defaultManager];
        [fm removeItemAtPath:path error:nil];//删除压缩包
        
        NSArray *images = [fm contentsOfDirectoryAtPath:upzipPath error:nil];
        
        if (images.count>0) {
            NSMutableArray *imagePaths = [[NSMutableArray alloc] init];
            
            for (NSString *image in images) {
                
                NSString *url = [upzipPath stringByAppendingPathComponent:image];
                NSLog(@"%@",url);
                MWPhoto *photo = [MWPhoto photoWithURL:[NSURL fileURLWithPath:url]];
                NSLog(@"%@",photo.caption);
                
                [imagePaths addObject:photo];
                
            }
            
            [self initPhotoBrowserWithImages:imagePaths];
        }
        
    }
    
    
}

#pragma mark - MWPhotoBrowser

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return self.photos.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < self.photos.count) {
        return [self.photos objectAtIndex:index];
    }
    return nil;
}


-(void)initPhotoBrowserWithImages:(NSArray *)images{
    
    [self.photos removeAllObjects];
    
    [self.photos addObjectsFromArray:images];
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    
    // Set options
    browser.displayActionButton = NO; // Show action button to allow sharing, copying, etc (defaults to YES)
    browser.displayNavArrows = NO; // Whether to display left and right nav arrows on toolbar (defaults to NO)
    browser.displaySelectionButtons = NO; // Whether selection buttons are shown on each image (defaults to NO)
    browser.zoomPhotosToFill = YES; // Images that almost fill the screen will be initially zoomed to fill (defaults to YES)
    browser.alwaysShowControls = NO; // Allows to control whether the bars and controls are always visible or whether they fade away to show the photo full (defaults to NO)
    browser.enableGrid = YES; // Whether to allow the viewing of all the photo thumbnails on a grid (defaults to YES)
    browser.startOnGrid = NO; // Whether to start on the grid of thumbnails instead of the first photo (defaults to NO)
    browser.autoPlayOnAppear = NO; // Auto-play first video
    
    // Customise selection images to change colours if required
    browser.customImageSelectedIconName = @"ImageSelected.png";
    browser.customImageSelectedSmallIconName = @"ImageSelectedSmall.png";
    
    // Optionally set the current visible photo before displaying
    [browser setCurrentPhotoIndex:0];
    
    // Present
    [self.navigationController pushViewController:browser animated:YES];
    
    // Manipulate
    [browser showNextPhotoAnimated:YES];
    [browser showPreviousPhotoAnimated:YES];
}

#pragma mark - tableview

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}


- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    //从选中中取消
    //    if (self.selectorPatnArray.count > 0) {
    //
    //        [self.selectorPatnArray removeObject:self.array[indexPath.row]];
    //    }
    NSDictionary *logs = self.logs[indexPath.row];
    
    [self.selectDatas removeObject:logs];
    
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *logs = self.logs[indexPath.row];
    
    if (self.tableView.isEditing) {
        
        [self.selectDatas addObject:logs];
    }else{
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        if (self.isAlarm) {
            [self downloadImages:logs];
        }else{
            NSString *bid = logs[@"bid"];
            //    NSString *aid = logs[@"aid"];
            NSString *fid = logs[@"fid"];
            
            NSURL *url = [YKBusinessFramework equesGetRingPictureUrl:bid fid:fid];
            NSMutableArray *imags = [[NSMutableArray alloc] init];
            [imags addObject:[MWPhoto photoWithURL:url]];
            [self initPhotoBrowserWithImages:imags];
        }
        
    }
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.logs.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 100;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    VisitorTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
    
    NSDictionary *logs = self.logs[indexPath.row];
    if (self.isAlarm) {
        long long time = [logs[@"time"] longLongValue]/1000;
        [self.dateFormatter setDateFormat:@"HH:mm:ss"];
        
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
        cell.timeLabel.text = [self.dateFormatter stringFromDate:date];
        cell.nameLabel.text = self.name;
        cell.typeLabel.text = self.isAlarm?self.typeButton.titleLabel.text:@"有人按门铃了";
        NSArray *pvids = logs[@"pvid"];
        if (pvids.count>0) {
            NSURL *url = [YKBusinessFramework equesGetThumbUrl:logs[@"bid"] pvid:pvids[0]];
            [cell.thumpButton sd_setImageWithURL:url forState:UIControlStateNormal placeholderImage:nil options:SDWebImageAllowInvalidSSLCertificates];
            
        }
    }else{
        long long time = [logs[@"ringtime"] longLongValue]/1000;
        [self.dateFormatter setDateFormat:@"HH:mm:ss"];
        
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
        cell.timeLabel.text = [self.dateFormatter stringFromDate:date];
        cell.nameLabel.text = self.name;
        cell.typeLabel.text = self.isAlarm?self.typeButton.titleLabel.text:@"有人按门铃了";
        NSURL *url = [YKBusinessFramework equesGetRingPictureUrl:logs[@"bid"] fid:logs[@"fid"]];
        [cell.thumpButton sd_setImageWithURL:url forState:UIControlStateNormal placeholderImage:nil options:SDWebImageAllowInvalidSSLCertificates];
    }
    
    return cell;
}

- (IBAction)buttonClick:(UIButton *)sender {
    
    if (self.tableView.isEditing) {
        return;
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    if (sender.tag==1) {
        PopCalendarViewController *vc= [[PopCalendarViewController alloc]  init];
        vc.currentDate = self.currentDate;
        vc.bid = self.deviceDict[@"bid"];
        vc.isAlarm = self.isAlarm;
        vc.isRings = !self.isAlarm;
        __weak typeof(self) weakSelf = self;
        vc.selectDateBlock = ^(NSDate *date) {
            
            [weakSelf refresh:date];
        };
        MZFormSheetPresentationViewController *sheet = [[MZFormSheetPresentationViewController alloc] initWithContentViewController:vc];
        sheet.presentationController.contentViewSize = CGSizeMake(SCREEN_WIDTH, 300);
        sheet.presentationController.shouldDismissOnBackgroundViewTap = NO;
        sheet.contentViewCornerRadius=0.f;
        sheet.presentationController.movementActionWhenKeyboardAppears = MZFormSheetActionWhenKeyboardAppearsCenterVertically;
        sheet.contentViewControllerTransitionStyle=MZFormSheetPresentationTransitionStyleSlideFromTop;
        sheet.presentationController.portraitTopInset=46+40;
        sheet.willDismissContentViewControllerHandler=^(UIViewController *v){
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMessageResult:) name:equesOnMessageResultNotification object:nil];
            
        };
        
        [self presentViewController:sheet animated:YES completion:nil];
        
    }
}
@end
